package com.oauth2.provider.config;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Bean;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;


@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	
	public SecurityConfig() {
		System.out.println("SecurityConfig.....");
	}
	
	@Bean
	public static PasswordEncoder passwordEncoder() {
		return NoOpPasswordEncoder.getInstance();
	}

	@Bean
	@Override
	public AuthenticationManager authenticationManagerBean() throws Exception {
		return super.authenticationManagerBean();
	}

	@Override
	public void configure(WebSecurity web) {
		web.ignoring().antMatchers("/resource/**");
	}

	@Override
	public void configure(HttpSecurity http) throws Exception {
		http.csrf().disable();
		
		http.requestMatchers().antMatchers("/oauth/**","/rest/**")
		.and()
		.authorizeRequests()
		.antMatchers("/oauth/**","/rest/**").permitAll();
		
		http.exceptionHandling()
		.accessDeniedHandler(new AccessDeniedHandler() {
			@Override
			public void handle(HttpServletRequest request, HttpServletResponse response,
					AccessDeniedException accessDeniedException) throws IOException, ServletException {
				accessDeniedException.printStackTrace();
			}
		})
		.authenticationEntryPoint(new AuthenticationEntryPoint() {
			@Override
			public void commence(HttpServletRequest request, HttpServletResponse response,
					AuthenticationException authException) throws IOException, ServletException {
				authException.printStackTrace();
			}
		});
		
		
	}

	@Override
	public void configure(AuthenticationManagerBuilder builder) throws Exception {
		builder.inMemoryAuthentication()
		.withUser("John").password("123456").roles("USER")
		.and()
		.withUser("Margaret").password("green").roles("USER", "ADMIN");
		// 自定义认证
		// builder.authenticationProvider(this.authenticationService);
	}

}
